<?php
declare (strict_types=1);

// +----------------------------------------------------------------------
// | SCApi
// +----------------------------------------------------------------------
// | 版权所有 2021~2022 贾二小 [ http://www.ipsoul.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.ipsoul.com
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免费声明 ( http://doc.ipsoul.com/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/jiaerxiao/scapi
// | github 代码仓库：https://github.com/jiaerxiao/scapi
// +----------------------------------------------------------------------

namespace app\system\service;

use app\common\service\BaseService;
use app\common\service\ToolService;
use app\system\facade\UserRoleFacade;
use think\App;
use think\facade\Db;

class UserService extends BaseService
{
    /**
     * 初始化
     * @param App $app
     */
    public function __construct(App $app)
    {
        parent::__construct($app, '用户管理', 'user');
    }

    /**
     * 用户登录
     * @param array $paramData 登录信息
     * @author 贾二小
     * @since 2021/12/12
     */
    public function loginByAccount(array $paramData): array
    {
        $userData = $this->getInfoByAccount($paramData['username']);
        if (empty($userData)) {
            ToolService::error('当前用户名不存在');
        }
        if ($userData['password'] != $paramData['password']) {
            ToolService::error('用户名密码不正确');
        }
        unset($userData['password']);
        //设置登录首页显示图
        $userData['dashboard'] = 0;
        //获取用户接口权限
        $userData['role'] = [];

        //更新登录信息(最后登录时间和IP)
        $this->updateLoginInfo($userData['id']);

        //返回数据
        $data = [];
        $data['token'] = get_token($paramData['username']);
        $data['userInfo'] = $userData;
        //设置缓存
        cache($data['token'], $userData, 7200);
        return $data;
    }

    /**
     * 根据用户名获取用户信息
     * @author 贾二小
     * @since 2021/11/7
     */
    private function getInfoByAccount(string $userName)
    {
        $map = [];
        $map[] = [$this->config['tableAlias'] . '.userName', '=', $userName];
        return $this->info($map);
    }

    /**
     * 用户登录成功更新
     * @author 贾二小
     * @since 2021/11/20
     */
    private function updateLoginInfo(int $id): void
    {
        $data = [];
        $data['last_login_time'] = date('Y-m-d H:i:s');
        $data['last_login_ip'] = ToolService::getClientIp(0, true);
        $this->updateById($id, $data);
    }

    /**
     * 表格数据
     * @author 贾二小
     * @since 2021/11/20
     */
    public function tableList(array $paramData): array
    {
        $map = [];
        if (isset($paramData['groupId']) && !empty($paramData['groupId'])) {
            $map[] = ['id', 'in', UserRoleFacade::list([['role_id', '=', $paramData['groupId']]])->column('userId')];
        }
        if (isset($paramData['name']) && !empty($paramData['name'])) {
            $map[] = ['userName|name', 'like', '%' . $paramData['name'] . '%'];
        }
        $this->config['tableField'] = ['id', 'avatar', 'userName', 'name', 'sex', 'mail', 'about', 'birthday', 'lastLoginTime', 'lastLoginIp', 'createUserId', 'createDate', 'updateUserId', 'updateDate', 'isDelete'];
        $data = $this->table($map);
        //没有数据时，直接返回
        if($data['total'] == 0) return $data;
        $dataId = implode(",",$data['rows']->column('id'));
        $sql = "SELECT ur.user_id,GROUP_CONCAT(ur.role_id) as roleId,GROUP_CONCAT(r.parent_ids separator '|') as roleParentIds,GROUP_CONCAT(r.label) as roleLabel FROM sys_role r INNER JOIN sys_user_role ur ON r.id = ur.role_id WHERE r.is_delete = 0 AND ur.user_id IN ({$dataId}) GROUP BY ur.user_id";
        $roleIdList = $this->query($sql,[]);
        $data['rows'] = array_map(function ($item) use ($roleIdList) {
            foreach ($roleIdList as $vo) {
                if ($item['id'] == $vo['userId']) {
                    $itemGroup = array_map(function ($item) {
                        return json_decode($item, true);
                    }, explode('|', $vo['roleParentIds']));
                    $roleId = explode(',', $vo['roleId']);
                    foreach ($roleId as $role_key => $role_id) {
                        if (count($itemGroup[$role_key]) > 1) {
                            array_shift($itemGroup[$role_key]);
                            $item['group'][$role_key] = $itemGroup[$role_key];
                        }
                        $item['group'][$role_key][] = intval($role_id);
                    }

                    $item['groupName'] = $vo['roleLabel'];
                }
            }
            return $item;
        }, $data['rows']->toArray());
        return $data;
    }

    /**
     * 保存&更新
     * @author 贾二小
     * @since 2021/12/13
     */
    public function saving(array $paramData): array
    {
        $this->transaction(function () use (&$paramData) {
            $group = $paramData['group'];
            unset($paramData['group']);
            if (isset($paramData['id']) && $paramData['id'] > 0) {
                $this->updateById($paramData['id'], $paramData);
            } else {
                $paramData['id'] = $this->insertGetId($paramData);
            }
            $id = $paramData['id'];
            //删除原角色，新增现角色
            $roleData = array_map(function ($item) use ($id) {
                return ['user_id' => $id, 'role_id' => array_pop($item)];
            }, $group);
            $map = [];
            $map[] = ['user_id', '=', $id];
            UserRoleFacade::deleteByMap($map);
            UserRoleFacade::insertAll($roleData);
        });
        return $paramData;
    }

    /**
     * 密码重置
     * 重置为123456
     * @author 贾二小
     * @since 2022/1/3
     */
    public function passwordReset(array $ids)
    {
        $data = [];
        $data['password'] = 'e10adc3949ba59abbe56e057f20f883e';
        $map = [];
        $map[] = ['id', 'in', $ids];
        return $this->updateData($data, $map);
    }
}